package org.ym.tools.adapter;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

/**
 * 序列化/反序列化枚举
 * @author ym
 */
public class GsonEnumAdapter<E extends GsonEnum> extends TypeAdapter<E> {
    private final GsonEnum<E> gsonEnum;

    public GsonEnumAdapter(GsonEnum<E> gsonEnum){
        this.gsonEnum = gsonEnum;
    }
    @Override
    public void write(JsonWriter out, E value) throws IOException {
        if(value != null) {
            out.value(value.serialize());
        }else{
            out.value("");
        }
    }

    @Override
    public E read(JsonReader in) throws IOException {
        String value = in.nextString();
        return gsonEnum.deserialize(value);
    }
}
